from ninja import Router
from wechatpy import WeChatPay

from apps.schemas import R
from models.models import OrderInfo, VipOrderInfo
from utils.decorators import handle_exception
from water_applets import settings

wx_callback_router = Router(tags=["微信支付回调"])


@wx_callback_router.get("/wx/order/payment/wxnotify", summary="支付结果回调地址")
@handle_exception("支付失败")
def order_payment_notify(request):
    pay = WeChatPay(appid=settings.WECHAT_APPID, api_key=settings.WECHAT_MERCHANT_KEY,
                    sub_appid="", mch_id=settings.WECHAT_MERCHANT_ID)
    data = pay.parse_payment_result(request.data)
    order = OrderInfo.objects.get(order_id=data.get("out_trade_no"))
    order.transaction_status = 3
    order.save()
    good_spec = order.good_spec
    good_spec.inventory -= 1
    good_spec.save()
    order.user.in_come += order.good_spec.price * order.good_number
    return R.ok(msg="支付成功")


@wx_callback_router.get("/wx/vip_order/payment/wxnotify", summary="支付结果回调地址")
@handle_exception("支付失败")
def vip_order_payment_notify(request):
    pay = WeChatPay(appid=settings.WECHAT_APPID, api_key=settings.WECHAT_MERCHANT_KEY,
                    sub_appid="", mch_id=settings.WECHAT_MERCHANT_ID)
    data = pay.parse_payment_result(request.data)
    order = VipOrderInfo.objects.get(order_id=data.get("out_trade_no"))
    order.transaction_status = 3
    order.save()
    return R.ok(msg="支付成功")
